package wang.z.JFrame;

import wang.z.model.ResultInfo;
import wang.z.net.FailListener;
import wang.z.net.GetUtils;
import wang.z.net.PostUtils;
import wang.z.net.SuccessListener;
import wang.z.utils.JsonUtils;
import wang.z.utils.ResultInfoData2Vector;
import wang.z.utils.ScreenUtils;
import wang.z.utils.toolUtil;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import static javax.swing.JTable.AUTO_RESIZE_OFF;

/**
 * @author like
 * @date 2022/12/7 2:26
 * @Description TODO
 */
public class UserFace {
    final int WIDTH = 700;
    final int HEIGHT = 800;
    private JFrame jf = new JFrame();
    private JTextField textField_1;//输入自己喜爱的文本框
    private JButton btnBackBook; //借书按钮
    private JButton btnExitBook; //退出系统按钮
    private JTextField textField;//还书文本
    private JPanel panel_1;//借书表
    private JPanel panel;  //还书
    private JPanel panel_2;//书表
    private JPanel panel_3;//借书表

    private JButton button_1;//查询按钮
    private JButton button_2;//借书按钮
    //下拉列表
    private JComboBox comboBox;//下拉列表
    private JTable BookTable;//数表
    private Vector<Vector> bookDate;//书数据
    private JTable dbTable;//借书表
    private Vector<Vector> dbDate;//借书数据
    private Vector<Vector> AllDate = new Vector<>();//全部借书数据
    private Vector<Vector> AllType = new Vector<>();//全部类型数据AllDate
    //喜欢的条件
    private Map<String, String> params1 = new HashMap<>();
    //列表
    DefaultTableModel BookModel;//
    DefaultTableModel dbModel;//
    private JScrollPane jscrollpane1;//表格滚轮
    private JScrollPane jscrollpane2;
    private JLabel label;//编号
    private JLabel lblNewLabel;//编号借
    private JTextField textField_2;//输入文本编号借
    private JTextField textField_3;//输入文本书名借
    private JLabel labelUser;//欢迎你
    private JLabel labelHello;//用户名



    public void init(){

        //类型数据的接受
        typeDate();

        jf.setBounds((ScreenUtils.getScreenWidth() - WIDTH) / 2, (ScreenUtils.getScreenHeight() - HEIGHT) / 2, WIDTH, HEIGHT);


        panel_2 = new JPanel();
        panel_2.setBorder(new TitledBorder(null, "\u4E66\u7C4D\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP, null, Color.RED));
        panel_2.setBounds(23, 400, 651, 240);

        panel_2.setLayout(null);
        textField_1 = new JTextField();
        textField_1.setColumns(10);
        textField_1.setBounds(252, 23, 135, 27);
        panel_2.add(textField_1);
        button_1 = new JButton("查询");

        button_1.setFont(new Font("幼圆", Font.BOLD, 16));
        button_1.setBounds(408, 20, 93, 33);
        panel_2.add(button_1);
        comboBox = new JComboBox();
        comboBox.setFont(new Font("幼圆", Font.BOLD, 15));
        comboBox.setBounds(123, 26, 109, 24);
        comboBox.addItem("书籍名称");
        comboBox.addItem("书籍作者");

        panel_2.add(comboBox);
        String[] BookTitle1 = {"编号", "书名", "类型", "作者", "出版社", "图书价格", "图书数量", "借阅状态", "描述"};
        Vector BookTitle = new Vector();
        for (String i : BookTitle1) {
            BookTitle.add(i);
        }
        /*具体的各栏行记录 先用空的二维数组占位*/
        //String[][] BookDates = {};
        bookDate = new Vector<Vector>();

        BookModel = new DefaultTableModel(bookDate, BookTitle);
        BookTable = new JTable(BookModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        //设置只能选中一行
        BookTable.getSelectionModel().setSelectionMode(AUTO_RESIZE_OFF);

        BookTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        TableColumn column = BookTable.getColumn(BookTitle.get(1));
        column.setMinWidth(100);
        BookTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        TableColumn column1 = BookTable.getColumn(BookTitle.get(8));
        column1.setMinWidth(100);
        tableDate();
        button_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                params1 = new HashMap<>();
                String text = textField_1.getText().trim();
                params1.put("text", text);
                params1.put("type", comboBox.getSelectedItem().toString());
                likeDate(params1);

            }
        });


        jscrollpane1 = new JScrollPane();
        jscrollpane1.setBounds(22, 74, 607, 140);
        jscrollpane1.setViewportView(BookTable);
        panel_2.add(jscrollpane1);


        panel_3 = new JPanel();
        panel_3.setBorder(new TitledBorder(null, "\u501F\u4E66",
                TitledBorder.LEADING, TitledBorder.TOP, null, Color.RED));

        panel_3.setBounds(23, 650, 650, 100);

        panel_3.setLayout(null);
        label = new JLabel("编号：");
        label.setFont(new Font("幼圆", Font.BOLD, 15));
        label.setBounds(68, 31, 48, 33);
        panel_3.add(label);
        textField_2 = new JTextField();
        textField_2.setEditable(false);
        textField_2.setColumns(10);
        textField_2.setBounds(126, 34, 135, 27);
        panel_3.add(textField_2);
        JLabel label_1 = new JLabel("书名：");
        label_1.setFont(new Font("幼圆", Font.BOLD, 15));
        label_1.setBounds(281, 31, 48, 33);


        panel_3.add(label_1);
        textField_3 = new JTextField();
        textField_3.setEditable(false);
        textField_3.setColumns(10);
        textField_3.setBounds(339, 34, 135, 27);
        panel_3.add(textField_3);
        button_2 = new JButton("借书");
        button_2.setFont(new Font("幼圆", Font.BOLD, 16));
        button_2.setBounds(495, 31, 80, 33);
        panel_3.add(button_2);
        BookTable.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectedRow = BookTable.getSelectedRow();
                String id = BookModel.getValueAt(selectedRow, 0).toString();
                String name = BookModel.getValueAt(selectedRow, 1).toString();
                textField_2.setText(id);
                textField_3.setText(name);
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
        button_2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取选中的条目
                int selectedRow = BookTable.getSelectedRow();//如果有选中的条目，则返回条目的行号，如果没有选中，那么返回-1

                if (selectedRow == -1) {
                    JOptionPane.showMessageDialog(jf, "请选择要借阅的条目！");
                    return;
                }

                //防止误操作
                int result = JOptionPane.showConfirmDialog(jf, "确认要借阅选中的条目吗？", "确认借阅", JOptionPane.YES_NO_OPTION);
                if (result != JOptionPane.YES_OPTION) {
                    return;
                }

                String id = BookModel.getValueAt(selectedRow, 0).toString();

                GetUtils.get("http://localhost:8080/borrow_detail/book?id=" + id, new SuccessListener() {
                    @Override
                    public void success(String result) throws IOException {
                        ResultInfo info = JsonUtils.parseResult(result);
                        if (info.isFlag()) {
                            dbTable();
                            JOptionPane.showMessageDialog(jf, "借阅成功");
                            String text = textField_1.getText().trim();
                            if (text != null && text.length() > 0) {
                                likeDate(params1);
                            } else {
                                tableDate();
                            }
                        } else {
                            JOptionPane.showMessageDialog(jf, info.getMessage());
                            if(info.getMessage().equals("用户尚未登录")){
                                new loginFrm().init();
                                jf.dispose();
                            }
                        }

                    }
                }, new FailListener() {
                    @Override
                    public void fail() {
                        JOptionPane.showMessageDialog(jf, "网络异常，请稍后重试");
                    }
                });

            }
        });
        panel_1 = new JPanel();
        panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
                "\u501F\u9605\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP,
                null, new Color(255, 0, 0)));
        panel_1.setBounds(23, 48, 651, 200);
        /*做一个表头栏数据  一维数组* */
        String[] bdTitle1 = {"编号", "书名", "状态", "借书时间", "还书时间",};
        Vector bdTitle = new Vector();
        for (String i : bdTitle1) {
            bdTitle.add(i);
        }
        /*具体的各栏行记录 先用空的二维数组占位*/
        dbDate = new Vector<>();
        dbModel = new DefaultTableModel(dbDate, bdTitle);
        dbTable = new JTable(dbModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        dbTable.getSelectionModel().setSelectionMode(AUTO_RESIZE_OFF);
        panel_1.add(dbTable);

        panel_1.setLayout(null);
        jscrollpane2 = new JScrollPane();
        jscrollpane2.setBounds(22, 30, 607, 140);
        jscrollpane2.setViewportView(dbTable);
        panel_1.add(jscrollpane2);

        panel = new JPanel();
        panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "\u8FD8\u4E66",
                TitledBorder.LEADING, TitledBorder.TOP, null, new Color(255, 0, 0)));
        panel.setBounds(23, 280, 651, 100);
        jf.getContentPane().add(panel);
        panel.setLayout(null);
        lblNewLabel = new JLabel("编号：");
        lblNewLabel.setBounds(90, 25, 51, 27);
        panel.add(lblNewLabel);
        lblNewLabel.setFont(new Font("幼圆", Font.BOLD, 16));
        textField = new JTextField();
        textField.setBounds(145, 28, 116, 24);
        textField.setEditable(false);
        panel.add(textField);
        textField.setColumns(10);
        btnBackBook = new JButton("还书");
        dbTable.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectedRow = dbTable.getSelectedRow();
                String id = dbModel.getValueAt(selectedRow, 0).toString();
                textField.setText(id);
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
        btnBackBook.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取选中的条目
                int selectedRow = dbTable.getSelectedRow();//如果有选中的条目，则返回条目的行号，如果没有选中，那么返回-1

                if (selectedRow == -1) {
                    JOptionPane.showMessageDialog(jf, "请选择要还书的条目！");
                    return;
                }
                if((dbTable.getValueAt(selectedRow,2).equals("已归还"))){
                    JOptionPane.showMessageDialog(jf, "已经归还了，请重新选择！");
                    return;
                }

                //防止误操作
                int result = JOptionPane.showConfirmDialog(jf, "确认要还选中的条目吗？", "确认还书", JOptionPane.YES_NO_OPTION);
                if (result != JOptionPane.YES_OPTION) {
                    return;
                }

                String id = dbTable.getValueAt(selectedRow, 0).toString();
                String bookName = dbModel.getValueAt(selectedRow, 1).toString();
                GetUtils.get("http://localhost:8080/borrow_detail/reBook?id=" + id+"&bookName="+bookName, new SuccessListener() {
                    @Override
                    public void success(String result) throws IOException {
                        ResultInfo info = JsonUtils.parseResult(result);
                        if (info.isFlag()) {
                            dbTable();
                            String text = textField.getText().trim();
                            if (text != null && text.length() > 0) {
                                likeDate(params1);
                            } else {
                                tableDate();
                            }
                            JOptionPane.showMessageDialog(jf, "还书成功");
                        } else {

                            JOptionPane.showMessageDialog(jf, info.getMessage());
                            if(info.getMessage().equals("用户尚未登录")){
                                new loginFrm().init();
                                jf.dispose();
                            }
                        }

                    }
                }, new FailListener() {
                    @Override
                    public void fail() {
                        JOptionPane.showMessageDialog(jf, "网络异常，请稍后重试");
                    }
                });

            }
        });
        btnBackBook.setFont(new Font("幼圆", Font.BOLD, 15));
        btnBackBook.setBounds(299, 25, 85, 31);

        btnExitBook = new JButton("退出系统");
        btnExitBook.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = JOptionPane.showConfirmDialog(jf, "确认要退出系统？", "确认退出", JOptionPane.YES_NO_OPTION);
                if(result != JOptionPane.YES_OPTION) {
                    return;
                }
                System.exit(0);

            }
        });
        btnExitBook.setFont(new Font("幼圆", Font.BOLD, 15));
        btnExitBook.setBounds(415, 25, 170, 31);
        panel.add(btnExitBook);
        panel.add(btnBackBook);


        dbTable();

        labelHello = new JLabel("欢迎您");
        labelHello.setFont(new Font("幼圆", Font.BOLD, 15));
        labelHello.setBounds(200, 10, 48, 33);
        labelUser = new JLabel("");
        labelUser.setFont(new Font("幼圆", Font.BOLD, 15));
        labelUser.setBounds(250, 10, 48, 33);
        labelUser.setForeground(Color.RED);
        getUser();
        jf.add(labelHello);
        jf.add(labelUser);
        jf.add(panel_1);
        jf.add(panel);
        jf.add(panel_2);
        jf.add(panel_3);

        JPanel panel1 = new JPanel();
        jf.add(panel1);
        jf.setVisible(true);
    }


    public static Vector<Vector> tranvector(Vector<Vector> vector) {
        for (Vector ve : vector) {
            int o = (int) ve.get(7);
            if (o == 1) {
                ve.set(7, "起售");
            } else {
                ve.set(7, "停售");
            }
        }
        return vector;
    }

    public static Vector<Vector> dbtranvector(Vector<Vector> vector) {
        for (Vector ve : vector) {
            ve.set(4, toolUtil.getDateByTime((ArrayList<Integer>) ve.get(4)));
            ve.set(5, toolUtil.getDateByTime((ArrayList<Integer>) ve.get(5)));
            int o = (int) ve.get(3);
            if (o == 1) {
                ve.set(3, "已归还");
            }else
            {
                ve.set(3, "未归还");
            }
            ve.remove(1);


        }
        return vector;
    }


public void getUser(){
        PostUtils.post("http://localhost:8080/user/getByName", new SuccessListener() {
                    //请求发送成功，服务器正常响应，会执行这里
                    @Override
                    public void success(String result) throws IOException {//result参数就是服务器响应回来的json字符串
                        ResultInfo info = JsonUtils.parseResult(result);
                        //判断info中的flag标记
                        if (info.isFlag()) {
                            labelUser.setText(info.getData().toString());
                        } else {
                            JOptionPane.showMessageDialog(jf, info.getMessage());
                            if(info.getMessage().equals("用户尚未登录")){
                                new loginFrm().init();
                                jf.dispose();
                            }
                        }
                    }
                }
                , new FailListener() {
                    //当该请求发送失败后会执行这个方法
                    @Override
                    public void fail() {
                        JOptionPane.showMessageDialog(jf, "网络异常，请稍后重试");
                    }
                }
        );
    }
    public void  dbTable() {
        PostUtils.post("http://localhost:8080/borrow_detail/findAlldb", new SuccessListener() {
                    //请求发送成功，服务器正常响应，会执行这里
                    @Override
                    public void success(String result) throws IOException {//result参数就是服务器响应回来的json字符串
                        ResultInfo info = JsonUtils.parseResult(result);
                        //判断info中的flag标记
                        if (info.isFlag()) {

                            Vector<Vector> vectors = ResultInfoData2Vector.convertResultInfoData2Vector(info);
                            Vector<Vector> tranvector = dbtranvector(vectors);
                            //清空tableData的数据
                            dbDate.clear();

                            //类型id和书名对应
                            for (Vector vector : tranvector) {
                                for (Vector vector1 : AllDate) {
                                    if (vector1.get(0).equals(vector.get(1))) {
                                            vector.set(1, vector1.get(1));
                                    }
                                }
                                dbDate.add(vector);
                            }

                            //刷新表格
                            dbModel.fireTableDataChanged();
                        } else {
                            if(dbDate.size() != 0){
                                JOptionPane.showMessageDialog(jf, info.getMessage());
                            }

                            if(info.getMessage().equals("用户尚未登录")){

                                new loginFrm().init();
                                jf.dispose();
                            }
                        }
                    }
                }
                , new FailListener() {
                    //当该请求发送失败后会执行这个方法
                    @Override
                    public void fail() {
                        JOptionPane.showMessageDialog(jf, "网络异常，请稍后重试");
                    }
                }
        );
    }

    public void tableDate() {
        PostUtils.post("http://localhost:8080/book/findAll", new SuccessListener() {
                    //请求发送成功，服务器正常响应，会执行这里
                    @Override
                    public void success(String result) throws IOException {//result参数就是服务器响应回来的json字符串
                        ResultInfo info = JsonUtils.parseResult(result);
                        //判断info中的flag标记
                        if (info.isFlag()) {
                            Vector<Vector> vectors = ResultInfoData2Vector.convertResultInfoData2Vector(info);
                            Vector<Vector> tranvector = tranvector(vectors);
                            //清空tableData的数据
                            bookDate.clear();
                            for (Vector vector : tranvector) {
                                bookDate.add(vector);
                                AllDate.add(vector);
                            }
                            typeChanged();
                            //刷新表格
                            BookModel.fireTableDataChanged();
                        } else {
                            JOptionPane.showMessageDialog(jf, info.getMessage());
                            if(info.getMessage().equals("用户尚未登录")){
                                new loginFrm().init();
                                jf.dispose();
                            }
                            JOptionPane.showMessageDialog(jf, info.getMessage());



                        }
                    }
                }
                , new FailListener() {
                    //当该请求发送失败后会执行这个方法
                    @Override
                    public void fail() {
                        JOptionPane.showMessageDialog(jf, "网络异常，请稍后重试");
                    }
                }
        );
    }
    public void likeDate(Map<String, String> params) {
        PostUtils.postWithParams("http://localhost:8080/book/getbylike", params, new SuccessListener() {
            @Override
            public void success(String result) throws IOException {
                ResultInfo info = JsonUtils.parseResult(result);
                if (info.isFlag()) {
                    //消息转换
                    Vector<Vector> vectors = ResultInfoData2Vector.convertResultInfoData2Vector(info);
                    vectors = tranvector(vectors);
                    //清空tableData的数据
                    bookDate.clear();
                    for (Vector vector : vectors) {
                        bookDate.add(vector);
                    }
                    typeChanged();
                    //刷新表格
                    BookModel.fireTableDataChanged();
                } else {
                    JOptionPane.showMessageDialog(jf, info.getMessage());
                    if(info.getMessage().equals("用户尚未登录")){
                        new loginFrm().init();
                        jf.dispose();
                    }
                }
            }
        }, new FailListener() {
            @Override
            public void fail() {
                JOptionPane.showMessageDialog(jf, "网络异常，请稍后重试");
            }
        });
    }
    public void typeDate() {
        PostUtils.post("http://localhost:8080/book_type/getAll", new SuccessListener() {
            @Override
            public void success(String result) throws IOException {
                ResultInfo info = JsonUtils.parseResult(result);
                if (info.isFlag()) {
                    //消息转换
                    Vector<Vector> vectors = ResultInfoData2Vector.convertResultInfoData2Vector(info);
                    for (Vector vector : vectors) {
                        AllType.add(vector);
                    }
                } else {
                    JOptionPane.showMessageDialog(jf, info.getMessage());
                    if(info.getMessage().equals("用户尚未登录")){
                        new loginFrm().init();
                        jf.dispose();
                    }
                }
            }
        }, new FailListener() {
            @Override
            public void fail() {
                JOptionPane.showMessageDialog(jf, "网络异常，请稍后重试");
            }
        });
    }
    public  void typeChanged(){
        for (Vector vector : bookDate) {
            for (Vector AllType : AllType) {
                if (AllType.get(0).equals(vector.get(2))){
                    vector.set(2,AllType.get(1));
                }

            }
        }
    }
}
